<template>
  <div id="flow-success-order">
    <div class="search-box">
      <el-form>
        <el-form-item label="店铺名称：">
          <el-select
            :class="msgLight?'msgLight':''"
            v-model="searchForm.shopId"
            placeholder="请选择店铺"
            size="small"
            filterable
            :filter-method="dataFilter"
            clearable
          >
            <el-option
              v-for="(item, index) in shopNameList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划ID：">
          <el-input
            placeholder="请输入计划ID"
            v-model="searchForm.planCode"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="任务ID：">
          <el-input
            placeholder="请输入任务ID"
            v-model="searchForm.taskCode"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="商品ID：">
          <el-input
            placeholder="请输入商品ID"
            v-model="searchForm.productId"
            size="small"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="关键词：">
          <el-input
            placeholder="请输入关键词"
            v-model="searchForm.keyword"
            size="small"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="任务类型 ：">
          <el-select
            v-model="searchForm.flowTaskType"
            placeholder="请选择类型"
            size="small"
          >
            <el-option
              v-for="(item, index) in flowTaskType"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="完成时间 ：">
          <el-date-picker
            format="yyyy-MM-dd HH:mm:ss"
            value-format="timestamp"
            size="small"
            v-model="searchTime"
            @change="changeTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
            :style="msgLight2?'border:1px solid red;':''"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="审核时间 ：">
          <el-date-picker
            format="yyyy-MM-dd HH:mm:ss"
            value-format="timestamp"
            size="small"
            v-model="checkTime"
            @change="changeCheckTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            class="search-btn"
            icon="el-icon-ali-search"
            @click="searchData"
            >查&nbsp;询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            class="reset-btn"
            icon="el-icon-ali-reset"
            @click="resetSearchParam"
            >重&nbsp;置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box">
      <el-table border :data="tableData" max-height="580px">
        <el-table-column prop="platform_type" label="店铺类型/店铺名称">
          <div slot-scope="scope">
            <div class="textColor">{{ getShopType(scope.row) }}</div>
            <div>{{ scope.row.shop_name }}</div>
          </div>
        </el-table-column>
        <el-table-column width="120px" prop="goods_img" label="商品主图">
          <el-popover
            placement="right"
            trigger="hover"
            slot-scope="scope"
            v-if="scope.row.goods_img"
          >
            <img class="goods-preview-img" :src="scope.row.goods_img" />
            <img
              slot="reference"
              :src="scope.row.goods_img"
              style="width: 80px;height: 80px"
            />
          </el-popover>
        </el-table-column>
        <el-table-column prop="tb_name" label="推手账号"></el-table-column>
        <el-table-column prop="product_id" label="商品ID"></el-table-column>
        <el-table-column
          width="100px"
          prop="all_commission"
          label="佣金"
        ></el-table-column>
        <el-table-column
          prop="flow_task_type"
          label="任务类型"
          :formatter="getFlowTaskType"
        ></el-table-column>
        <el-table-column
          width="120px"
          prop="entrance_type"
          label="入口类型"
          :formatter="getEntranceType"
        ></el-table-column>
        <el-table-column prop="keyword" label="关键词">
          <el-popover
            placement="right"
            trigger="hover"
            slot-scope="scope"
            v-if="scope.row.entrance_type == 3"
          >
            <img class="keyword-preview-img" :src="scope.row.keyword" />
            <img
              slot="reference"
              :src="scope.row.keyword"
              style="width: 80px;height: 80px"
            />
          </el-popover>
          <div v-else>
            {{ scope.row.keyword }}
          </div>
        </el-table-column>
        <el-table-column prop="begin_time" label="完成时间/审核时间">
          <div slot-scope="scope">
            <div>{{ scope.row.over_time }}</div>
            <div>{{ scope.row.check_time }}</div>
          </div>
        </el-table-column>
        <el-table-column prop="plan_code" label="计划ID/任务ID">
          <div slot-scope="scope">
            <div
              class="planCodeStyle"
              @click="toPlanDetailPage(scope.row.plan_id)"
            >
              {{ scope.row.plan_code }}
            </div>
            <div>{{ scope.row.task_code }}</div>
          </div>
        </el-table-column>
        <el-table-column width="120px" prop="goods_img" label="收藏图">
          <el-popover
            placement="right"
            trigger="hover"
            slot-scope="scope"
            v-if="scope.row.collect_img"
          >
            <img class="user-preview-img" :src="scope.row.collect_img" />
            <img
              slot="reference"
              :src="scope.row.collect_img"
              style="width: 80px;height: 80px"
            />
          </el-popover>
        </el-table-column>
        <el-table-column width="120px" prop="goods_img" label="加购图">
          <el-popover
            placement="right"
            trigger="hover"
            slot-scope="scope"
            v-if="scope.row.add_cart_img"
          >
            <img class="user-preview-img" :src="scope.row.add_cart_img" />
            <img
              slot="reference"
              :src="scope.row.add_cart_img"
              style="width: 80px;height: 80px"
            />
          </el-popover>
        </el-table-column>
        <el-table-column width="120px" prop="goods_img" label="关注图">
          <el-popover
            placement="right"
            trigger="hover"
            slot-scope="scope"
            v-if="scope.row.attention_img"
          >
            <img class="user-preview-img" :src="scope.row.attention_img" />
            <img
              slot="reference"
              :src="scope.row.attention_img"
              style="width: 80px;height: 80px"
            />
          </el-popover>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="100"
          class-name="shenghe"
        >
          <div slot-scope="scope">
            <el-button
              class="appeal-btn"
              v-if="scope.row.appeal_status == 4"
              size="mini"
              @click="openAppealOrder(scope.row)"
              >申诉</el-button
            >
            <div v-else>{{ appealStatus[scope.row.appeal_status] }}</div>
          </div>
        </el-table-column>
      </el-table>
      <el-table :data="allTableData" id="exportTable" border v-show="false">
        <el-table-column
          prop="shop_type"
          label="店铺类型"
          :formatter="getShopType"
        ></el-table-column>
        <el-table-column prop="shop_name" label="店铺名称"></el-table-column>
        <el-table-column prop="tb_name" label="推手账号"></el-table-column>
        <el-table-column prop="product_id" label="商品ID"></el-table-column>
        <el-table-column
          prop="flow_task_type"
          label="任务类型"
          :formatter="getFlowTaskType"
        ></el-table-column>
        <el-table-column prop="all_commission" label="佣金"></el-table-column>
        <el-table-column prop="over_time" label="完成时间"></el-table-column>
        <el-table-column prop="check_time" label="审核时间"></el-table-column>
        <el-table-column
          width="120px"
          prop="entrance_type"
          label="入口类型"
          :formatter="getEntranceType"
        ></el-table-column>
        <el-table-column prop="keyword" label="关键词"></el-table-column>
        <el-table-column prop="plan_code" label="计划ID"></el-table-column>
        <el-table-column prop="task_code" label="任务ID"></el-table-column>
      </el-table>
      <div class="table-footer">
        <el-popover
          placement="top-start"
          title="导出功能说明"
          width="200"
          trigger="hover"
        >
          <div>
            操作成功后会自动上锁60秒 <br>
            倒计时结束后，自动解锁
          </div>
          <el-button
            slot="reference"
            :icon="lock ? 'el-icon-download' : 'el-icon-ali-password'"
            class="download-btn"
            :style="lock ? '' : 'background:#ccc'"
            @click="exportFlowTaskDone"
            >{{ lock ? "导出" : dtime + " S" }}</el-button
          >
        </el-popover>
        <!-- <el-button
          icon="el-icon-download"
          class="download-btn"
          @click="downloadExcel"
          >导出</el-button
        > -->
        <el-pagination
          :page-sizes="[5, 10, 15, 20]"
          :page-size="searchForm.pageSize"
          :current-page="searchForm.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageToatal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>
    <v-appeal
      :appealForm="appealForm"
      @closeDialog="closeAppealDialog"
      @confrimAppeal="confrimAppeal"
      v-if="showAppealDialog"
    ></v-appeal>
  </div>
</template>

<script>
import {
  apiGetMerchantShopList,
  apiSuccessCheckFlowTaskList,
  apiExportFlowTaskDone, // 销量导出功能
  apiExportFlowTaskDownLoad
} from "../../request/api.js";
import { mapGetters, mapActions } from "vuex";
import vAppeal from "../../components/createAppeal.vue";
export default {
  components: {
    vAppeal
  },
  data() {
    return {
      msgLight:false,
      msgLight2:false,
      lock: true,
      dtime: 60,
      timer: null,
      searchForm: {
        token: "",
        page: 1,
        pageSize: 10,
        shopId: "",
        productId: "",
        planCode: "",
        taskCode: "",
        startTime: "",
        endTime: "",
        checkEndTime: "",
        checkStartTime: "",
        flowTaskType: "",
        keyword: "",
        shopType: ""
      },
      searchTime: [],
      checkTime: [],
      shopNameList: [],
      shopNameOptions: [],
      platformNameObject: {
        1: "淘宝",
        2: "天猫",
        3: "京东",
        4: "1688",
        13: "唯品会",
        15: "拼多多"
      },
      entranceType: {
        1: "关键词",
        2: "淘口令",
        3: "二维码",
        4: "直播",
        5: "其他"
      },
      flowTaskType: [
        {
          label: "浏览",
          value: 1
        },
        {
          label: "浏览+关注",
          value: 2
        },
        {
          label: "浏览+加购",
          value: 3
        },
        {
          label: "浏览+收藏",
          value: 4
        },
        {
          label: "浏览+加购+关注",
          value: 5
        },
        {
          label: "浏览+关注+收藏",
          value: 6
        },
        {
          label: "浏览+加购+收藏",
          value: 7
        },
        {
          label: "浏览+加购+收藏+关注",
          value: 8
        }
      ],
      pageToatal: 0,
      tableData: [],
      allTableData: [],
      showAppealDialog: false,
      appealForm: {},
      appealStatus: {
        1: "申诉已提交",
        2: "申诉正在处理",
        3: "申诉已完成"
      },
      pickerOptions: {
        disabledDate(time) {
          let merchantTime = window.localStorage.getItem("merchantTime");
          let curDate = new Date().getTime();
          let three = merchantTime * 24 * 3600 * 1000;
          let threeMonths = curDate - three;
          return time.getTime() < threeMonths;
        }
      },
      userToken: window.localStorage.getItem("token")
    };
  },
  created() {
    this.searchForm.token = this.userToken;
    this.searchForm.shopType = this.platformType;
    this.getCurTime();
    this.getShopList();
    this.getTableData();
  },
  computed: {
    ...mapGetters(["platformType"])
  },
  watch: {
    platformType: function(val) {
      this.searchForm.shopType = val;
      this.getTableData();
    },

    "searchForm.shopId": function() {
      this.$message("记得点击查询获取最新数据哦");
    },
    dtime() {
      if (this.dtime == 0) {
        this.lock = true;
        clearInterval(this.timer);
        this.dtime = 60;
      }
    }
  },
  methods: {
    ...mapActions(["setShopNameList"]),
    dataFilter(val) {
      this.searchForm.shopId = val;
      if (val) {
        //val存在
        this.shopNameList = this.shopNameOptions.filter(item => {
          if (
            !!~item.name.indexOf(val) ||
            !!~item.name.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        //val为空时，还原数组
        this.shopNameList = this.shopNameOptions;
      }
    },
    getShopList() {
      this.$isClick(true);
      apiGetMerchantShopList({
        token: this.userToken
      })
        .then(res => {
          this.$isClick(false);
          if (res.code == 1) {
            for (var i in res.msg.merchant_shop_list) {
              this.shopNameOptions.push({
                name:
                  this.platformNameObject[res.msg.merchant_shop_list[i].type] +
                  "-" +
                  res.msg.merchant_shop_list[i].name,
                id: res.msg.merchant_shop_list[i].id
              });
            }
            this.shopNameList = this.shopNameOptions;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(res => {
          this.$isClick(false);
          this.$message.error(res.msg);
        });
    },
    getTableData() {
      this.$isClick(true);
      apiSuccessCheckFlowTaskList(this.searchForm)
        .then(res => {
          this.$isClick(false);
          if (res.code == 1) {
            this.tableData = res.msg.res;
            this.pageToatal = res.msg.allNum;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(res => {
          this.$isClick(false);
          this.$message.error(res.msg);
        });
    },
    openAppealOrder(row) {
      this.appealForm = {
        token: this.userToken,
        task_type: 2,
        type: 1,
        order_num: row.order_num ? row.order_num : "",
        tb_name: row.tb_name,
        task_code: row.task_code,
        content: "",
        treat_content: "",
        proof_img_url: "",
        appeal_why: ""
      };
      this.showAppealDialog = true;
    },
    closeAppealDialog() {
      this.showAppealDialog = false;
    },
    confrimAppeal() {
      this.$message.success("申诉成功，请在申诉工单处查看");
      this.getTableData();
      this.showAppealDialog = false;
    },
    getCurTime() {
      var now = new Date();
      var startTime =
        new Date(new Date().toLocaleDateString()).getTime() -
        24 * 60 * 60 * 1000 * 6;
      var endTime =
        new Date(new Date().toLocaleDateString()).getTime() +
        24 * 60 * 60 * 1000 -
        1;
      this.searchTime = [startTime, endTime];
      this.searchForm.startTime = Math.floor(startTime / 1000);
      this.searchForm.endTime = Math.floor(endTime / 1000);
    },
    getFlowTaskType(row) {
      for (var i in this.flowTaskType) {
        if (this.flowTaskType[i].value == row.flow_task_type) {
          return this.flowTaskType[i].label;
        }
      }
    },
    getEntranceType(row) {
      return this.entranceType[row.entrance_type];
    },
    getShopType(row) {
      return this.platformNameObject[row.platform_type];
    },
    searchData() {
      this.searchForm.page = 1;
      this.searchForm.pageSize = 10;
      this.getTableData();
    },
    resetSearchParam() {
      this.searchForm = {
        token: this.userToken,
        page: 1,
        pageSize: 10,
        shopId: "",
        productId: "",
        planCode: "",
        taskCode: "",
        startTime: "",
        endTime: "",
        checkEndTime: "",
        checkStartTime: "",
        flowTaskType: "",
        keyword: "",
        shopType: this.platformType
      };
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.getTableData();
    },
    changeTime(val) {
      if (this.searchTime == null) {
        this.searchForm.startTime = "";
        this.searchForm.endTime = "";
      } else {
        this.dataDiff(val[0], val[1], "check");
        this.searchForm.startTime = this.changeTimeType(val[0]);
        this.searchForm.endTime = this.changeTimeType(val[1]);
      }
    },
    changeCheckTime(val) {
      if (this.checkTime == null) {
        this.searchForm.checkStartTime = "";
        this.searchForm.checkEndTime = "";
      } else {
        this.dataDiff(val[0], val[1], "check");
        this.searchForm.checkStartTime = this.changeTimestamp(val[0]);
        this.searchForm.checkEndTime = this.changeTimestamp(val[1]);
      }
    },
    dataDiff(startTime, endTime, type) {
      let diff = endTime - startTime;
      let t = 31 * 24 * 60 * 60 * 1000;
      if (diff > t) {
        this.$message.error("时间范围不能超过31天");
        if (type == "success") {
          this.completeTime = [];
        } else {
          this.checkTime = [];
        }

        return false;
      }
    },
    changeTimeType(time) {
      var d = new Date(time);
      var s =
        d.getFullYear() +
        "-" +
        (d.getMonth() + 1) +
        "-" +
        d.getDate() +
        " " +
        d.getHours() +
        ":" +
        d.getMinutes() +
        ":" +
        d.getSeconds();
      return new Date(s).getTime() / 1000;
    },
    toPlanDetailPage(id) {
      this.$router.push("/plan/flowPlanDetail?id=" + id);
    },
    getAllTableData() {
      let data = JSON.parse(JSON.stringify(this.searchForm));
      data.page = 1;
      data.pageSize = this.pageToatal;
      if (data.pageSize == 0) {
        this.$message.error("当前表格没有数据可以导出");
        return;
      }
      this.msgLight = false
      this.msgLight2 = false
      // 如果选择了店铺名，并且数据量超过500，提示请缩短任务完成时间
      if (data.pageSize > 500 && data.shopId) {
        this.msgLight2 = true
        this.$message.error(`当前数据:${data.pageSize}（条）,导出限制500条，请缩短任务完成时间`);
        return;
      }
      // 如果没选择店铺名，并且数据量超过500，提示选择店铺名
      else if (data.pageSize > 500 && !data.shopId) {
        this.$message(`请选择店铺`);
        this.msgLight = true
        return;
      }
      this.$message(`正在导出，请耐心等待...`);
      return new Promise(resolve => {
        this.$isClick(true);
        apiSuccessCheckFlowTaskList(data)
          .then(res => {
            this.$isClick(false);
            if (res.code == 1) {
              this.allTableData = res.msg.res;
              resolve(res);
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch(res => {
            this.$isClick(false);
            this.$message.error(res.msg);
          });
      });
    },
    downloadExcel() {
      var wb = "";
      var xlsxParam = { raw: true };
      this.getAllTableData().then(() => {
        this.$loading.show("下载中");

        wb = this.XLSX.utils.table_to_book(
          document.querySelector("#exportTable"),
          xlsxParam
        );
        var wbout = this.XLSX.write(wb, {
          bookType: "xlsx",
          bookSST: true,
          type: "array"
        });
        try {
          this.FileSaver.saveAs(
            new Blob([wbout], { type: "application/octet-stream" }),
            "流量已完成订单.xlsx"
          );
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        setTimeout(() => {
          this.$loading.hide();
          this.$message.success("下载完成");
        }, 1000);
        return wbout;
      });
    },
    exportFlowTaskDone() {
      if (!this.lock) {
        return;
      }
      this.lock = false;
      this.timer = setInterval(() => {
        this.dtime--;
      }, 1000);
      let respSplit = "";
      apiExportFlowTaskDone({
        token: this.userToken,
        getSplit: "",
        shopId:  this.searchForm.shopId || null,
        shopType:  this.searchForm.shopType || null,
        startTime:  this.searchForm.startTime || null,
        endTime:  this.searchForm.endTime || null
      }).then(res => {
        let obj = eval(res);
        if (obj.code != 200) {
          this.$message.error(obj.msg);
          return false;
        }
        if(obj.total==0){
          this.$message("没有可以导出的数据，请更换搜索条件或稍后重试");
          return false;
        }
        respSplit = obj.data;
        // this.$message("总数:" + obj.total + "|切成" + obj.split + "分");
        if(this.pageToatal!=obj.total){
          this.getTableData();
        }
        this.$confirm(
          "当前导出数据总数: " +
            obj.total +
            (obj.split > 1
              ? " ，为了加快导出速度，已智能分成 " +
                obj.split +
                " 个文件，确定导出吗？"
              : ""),
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info"
          }
        )
          .then(() => {
            let time = 0;
            let _this = this;
            this.$message.success("数据正在导出，请耐心等待");
            respSplit.forEach((element,index) => {
              setTimeout(function(){
                _this.getData(
                  element,
                  "商户已完成订单第" + element.page + "页",
                  obj.split
                );
                _this.$message("商户已完成订单第" + element.page + "页 准备中");
              },(index+1)%2==0?time+=5000:time)
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
            this.lock = true;
            this.dtime = 60;
            clearInterval(this.timer);
            return;
          });
      });
    },

    async getData(v, name, split) {
      this.$isClick(true);
      apiExportFlowTaskDownLoad({
        token: this.userToken,
        getData: "",
        endTime: v.endTime,
        page: v.page,
        pageSize: v.pageSize,
        shopId: v.shopId,
        shopType: v.shopType,
        startTime: v.startTime
      }).then(res => {
        this.$isClick(false);
        // this.$message(`当前下载进度${v.page}/${split}`)
        let blob = new Blob([res]);
        let a = document.createElement("a");
        a.download = name + ".csv";
        a.href = window.URL.createObjectURL(blob);
        a.click();
        this.$message.success("商户已完成订单第" + v.page + "页 已完成");
      });
    }
  }

};
</script>

<style lang="less">
#flow-success-order {
  .appeal-btn {
    background: @themeColor;
    color: #fff;
    padding: 8px 15px !important;
  }
}
.el-popover {
  .goods-preview-img,
  .keyword-preview-img {
    width: 200px;
    height: 200px;
  }
  .user-preview-img {
    width: 200px;
    height: 300px;
  }
}
.msgLight input{
  border:red  solid 1px;
}
</style>
